package com.yixin.hospital.filter;


import com.google.gson.Gson;
import com.yixin.hospital.common.ApiResult;
import com.yixin.hospital.common.Constant;
import com.yixin.hospital.enums.ResponseCodeEnum;
import com.yixin.hospital.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;


@WebFilter(urlPatterns = "/*")
@Component
public class JwtFilter implements Filter {
    @Value("${ip.white.list}")
    private List<String> ipWhiteList;
    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(
            Arrays.asList("/user/login", "/user/register", "/swagger-resources", "/webjars", "/v2", "/doc.html",
                    // 注册用
                    "/job/list",    // 职业下拉
                    "/job-title/job-job-title", // 职业-职称 联动
                    "/dept/dept-drop-list", // 部门下拉
                    "/work-address/dept-work-address",  //  部门-工作地点 联动
                    "/job-duty/dept-job-duty",   // 部门-职务 联动
                    "/job-type/list",   // 部门-职务 联动
                    "/job-office/list",   // 部门-职务 联动
                    "/websocket",   // websocket
                    "/user/user-dept-workAddress-jobOffice", // 手机号所在部门 工作地点 科室
                    "/audit-flow-preset/info" // 审批人， 用于注册
                    )));

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type, authorization");
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            filterChain.doFilter(request, response);
        }
        String requestURI = request.getRequestURI();
        boolean flag = false;
        for (String allowedPath : ALLOWED_PATHS) {
            flag = requestURI.startsWith(allowedPath);
            if (flag) break;
        }
        if (flag) {
            filterChain.doFilter(request, response);
            return;
        }

        // ip限制
//        if (!ipWhiteList.contains(ServletUtil.getClientIP(request))) {
//            response.getWriter().write(new Gson().toJson(ApiResult.error(ResponseCodeEnum.ILLEGAL_IP)));
//            return;
//        }

        String token = request.getHeader(Constant.AUTHORIZATION);
        if (token == null) {
            response.getWriter().write(new Gson().toJson(ApiResult.error(ResponseCodeEnum.ILLEGAL_TOKEN)));
            return;
        }

        ResponseCodeEnum responseCodeEnum = JwtUtil.verifyToken(token);
        if (responseCodeEnum != ResponseCodeEnum.SUCCESS) {
            response.getWriter().write(new Gson().toJson(ApiResult.error(responseCodeEnum)));
            return;
        }

        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
